package cn.lixin.hrm.service.impl;

import cn.lixin.hrm.constant.SMSConstant;
import cn.lixin.hrm.domain.VipUser;
import cn.lixin.hrm.dto.SMSCodeDto;
import cn.lixin.hrm.exception.GlobalException;
import cn.lixin.hrm.mapper.VipUserMapper;
import cn.lixin.hrm.service.IVerifyCodeService;
import cn.lixin.hrm.util.AssertUtils;
import cn.lixin.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipUserMapper vipUserMapper;
    @Override
    public String imageCode(String key) throws IOException {
        AssertUtils.isNull(key,"验证码key为空");
        // 字符串验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 图片验证码
        String encode = VerifyCodeUtils.VerifyCodePlus(code);
        // 存到redis
        redisTemplate.opsForValue().set(key,code,3L, TimeUnit.MINUTES);
        return encode;
    }

    @Override
    public void sendSMSCode(SMSCodeDto dto) {
        String mobile = dto.getMobile();
        // 空校验
        AssertUtils.isNull(mobile,"手机号为空");
        // 手机号是否被注册
        VipUser vipUser = new VipUser();
        vipUser.setPhone(mobile);
        VipUser user = vipUserMapper.selectOne(vipUser);
        if (user != null) {
            throw new GlobalException("手机号已经被注册");
        }
        // 图片验证码是否正确
        String imageCode = dto.getImageCode();
        // 校验验证码是否过期
        String codeKey = redisTemplate.opsForValue().get(dto.getImageCodeKey()).toString();
        AssertUtils.isNull(codeKey,"图形验证码过期");
        if (!imageCode.equalsIgnoreCase(codeKey)){
            throw new GlobalException("图形验证码错误");
        }
        String phoneCode = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
        // 将手机验证码存到Redis
        redisTemplate.opsForValue().set(SMSConstant.SMS_CONSTANT + mobile,phoneCode,3L,TimeUnit.MINUTES);
        //假装发送短信
        System.out.println("手机验证码为：【"+phoneCode+"】");

    }
}
